package com.taorenqi.business.fragment.login;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.taorenqi.business.R;
import com.taorenqi.business.activity.LoginActivity;
import com.taorenqi.business.activity.MainActivity;
import com.taorenqi.business.activity.PermissionsActivity;
import com.taorenqi.business.activity.base.BaseActivity;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.event.RechargeEvent;
import com.taorenqi.business.fragment.base.BaseMainFragment;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.utils.SpUtils;
import com.taorenqi.business.utils.StringUtils;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.data.cache.ACache;
import com.taorenqi.data.cache.EnumKey;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.login.LoginEntity;
import com.taorenqi.data.service.LoginDataHttpRequest;
import com.taorenqi.data.utils.PhoneUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.taorenqi.business.helper.Constant.LOGIN_PW;
import static com.taorenqi.business.helper.Constant.LOGIN_USER;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoginFragment extends BaseMainFragment {


    @Bind(R.id.iv_login_banner)
    ImageView ivLoginBanner;
    @Bind(R.id.et_login_phone)
    EditText etLoginPhone;
    @Bind(R.id.cb_login_isSaveUser)
    CheckBox cbLoginIsSaveUser;
    @Bind(R.id.et_login_pw)
    EditText etLoginPw;
    @Bind(R.id.cb_login_isShowPw)
    CheckBox cbLoginIsShowPw;
    @Bind(R.id.ll_login_login)
    LinearLayout llLoginLogin;
    @Bind(R.id.ll_login_registe)
    LinearLayout llLoginRegiste;
    @Bind(R.id.tv_login_forgetPw)
    TextView tvLoginForgetPw;

    private LoginActivity mContext;
    private Context mAppContext;

    private BasePageableResponse<LoginEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<LoginEntity>> subscriber;

    public static LoginFragment newInstance() {
        // Required empty public constructor
        LoginFragment fragment = new LoginFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActivity() instanceof BaseActivity) {
            mContext = (LoginActivity) getActivity();
        }
        mAppContext = MyApp.getApp().getApplicationContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        if (MyApp.getApp().getPermissionsChecker().lacksPermissions(MyApp.getApp().PHONE_STATE)) {
            PermissionsActivity.startActivityForResult(_mActivity, MyApp.getApp().REQUEST_CODE, MyApp.getApp().PHONE_STATE);
        }
        initView();
        initData();
        return view;
    }

    private void initView() {

        if (cbLoginIsSaveUser.isChecked()) {//要保存
            if (SpUtils.getString(mContext, LOGIN_USER) != null) {
                etLoginPhone.setText(SpUtils.getString(mContext, LOGIN_USER));
            }
            if (SpUtils.getString(mContext, LOGIN_PW) != null) {
                etLoginPw.setText(SpUtils.getString(mContext, LOGIN_PW));
            }
        }


        cbLoginIsShowPw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cbLoginIsShowPw.isChecked()) {
                    // 设置EditText文本为可见的
                    etLoginPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    // 设置EditText文本为隐藏的
                    etLoginPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                etLoginPw.postInvalidate();
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = etLoginPw.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }
        });
    }

    private void initData() {
        //登录
        subscriber = new PageDataSubscriberOnNext<BasePageableResponse<LoginEntity>>() {
            @Override
            public void onNext(BasePageableResponse<LoginEntity> entity) {
                //接口请求成功后处理
                data = entity;
                ACache.get(_mActivity).put(EnumKey.User.USER_TOKEN, data.getToken());
                Intent intent = new Intent();
                intent.setClass(mContext, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        };
    }


    @Subscribe
    public void onEvent(RechargeEvent event) {
       etLoginPhone.setText("");
       etLoginPw.setText("");
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.iv_login_banner, R.id.cb_login_isSaveUser, R.id.cb_login_isShowPw,
            R.id.ll_login_login, R.id.ll_login_registe,R.id.tv_login_forgetPw})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_login_banner:
                break;
            case R.id.cb_login_isSaveUser://保存用户名和密码
                break;
            case R.id.cb_login_isShowPw://显示密码
                break;
            case R.id.ll_login_login://登录
                submit();
                break;
            case R.id.ll_login_registe://注册页面
                start(RegisterFragment.newInstance());
                break;
            case R.id.tv_login_forgetPw://忘记密码
                start(FindbackPwdFragment.newInstance());
                break;
        }
    }

    private void submit() {
        String phone = etLoginPhone.getText().toString().trim();
        String password = etLoginPw.getText().toString().trim();
        String device = PhoneUtils.getPhoneIMEI(_mActivity);
        HashMap map = new HashMap();
        map.put("mobile", phone);
        map.put("password", password);
        map.put("device", device);
        String sign = Encoder.getSigns(map);

        if (cbLoginIsSaveUser.isChecked()) {
            SpUtils.putString(mContext, LOGIN_USER, phone);
            SpUtils.putString(mContext, LOGIN_PW, password);
        }else {
            SpUtils.putString(mContext, LOGIN_USER, "");
            SpUtils.putString(mContext, LOGIN_PW, "");
        }

        ACache.get(_mActivity).put(EnumKey.User.LOGIN_PWD, etLoginPw.getText().toString().trim());
        if (TextUtils.isEmpty(phone) || phone.length() < 11) {
            ToastUtil.showToast(mContext, "请输入正确手机号码");
        } else if (TextUtils.isEmpty(password)) {
            ToastUtil.showToast(mContext, "密码不能为空");
        }else {

            LoginDataHttpRequest.getInstance(MyApp.getApp()).postLogin(
                    new ProgressSubscriber(subscriber, mContext), phone,password, device,sign);
        }

    }

}
